/**
 *    Dashflix
 *    Copyright (C) 2008 Dashflix Project <http://code.google.com/p/dashflix>
 *    See LICENSE file for more on licensing.
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License along
 *    with this program; if not, write to the Free Software Foundation, Inc.,
 *    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/**
 * Global static strings - most fixes go here if Netflix makes changes.
 */

// The "." operator does not appear to be working properly.
// I can't make it match "\n" with /s, /m, or /sm.  And I
// can't group it with ANYTHING in [].  So I'm using 
// "[\d\D]" to mean "anything". - JE
var gNFUrl        = "http://www.netflix.com/Queue?" + (new Date()).getTime();
var gNFTitle      = "<title>Netflix: Queue</title>";
var gNFAtHome     = "<tr class='or'>[\\d\\D]+?</tr>";
var gNFInQ        = "<tr >[\\d\\D]+?</tr>";
var gNFMovieTitle = "href=\"([^\"]+)\"[^>]*?>([^<]+)";
var gNFMovieDate  = "<td class=\"ee estArr\">([\\d]+)/([\\d]+)/([\\d]+)";

var gReq;

if (window.widget) {
    widget.onshow = onshow;
    widget.onhide = onhide;
}

function onshow() {
    connect();
}

function onhide() {

}

function movieClicked(event) {
    return false;
}

function connect() {
    // Clean out output.
    document.getElementById("front-output").innerHTML = "";
    document.getElementById("back-output").innerHTML = "";

    // Start the spinner
    document.getElementById("spinner").style.display = "block";

    gReq = new XMLHttpRequest();
    gReq.onreadystatechange = handleResponse;

    gReq.open("GET", gNFUrl, true);
    gReq.send(null);
}

function handleResponse() {
    if (gReq.readyState == 4) {
        // Kill the spinner.
        document.getElementById("spinner").style.display = "none";
        if (gReq.status == 200) {
            //First we're going to check to see if the title of the
            //returned document is "Netflix: Queue".  If it's not,
            //either Netflix has changed its page or the user is not
            //logged in (and doesn't have the right cookies for this
            //to work.

            var response = gReq.responseText;
            if (!response.match(gNFTitle)) {
                var para = document.createElement("p");
                var text = document.createTextNode("Cannot find the cookies needed to log in to Netflix. You must use Safari log in to Netflix at least once before using this widget. ");

                var link = document.createElement("a");
                var linkText = document.createTextNode("Click here");
                link.href = "javascript:widget.openURL('http://www.netflix.com/Login')";
                link.appendChild(linkText);

                para.id = "error";
                para.appendChild(text);
                para.appendChild(link);
        
                text = document.createTextNode(" to log in now.");
                para.appendChild(text);

                document.getElementById("front-output").appendChild(para);    
                gFrontScrollArea.refresh();
                return;
            }

            var backref;
            var homeMovies = [];
            var queueMovies = [];

            var regex = new RegExp(gNFAtHome, "g");
            while (backref = regex.exec(response)) {
                homeMovies.push(backref[0]);
            }

            regex = new RegExp(gNFInQ, "g");
            while (backref = regex.exec(response)) {
               queueMovies.push(backref[0]);
            }

            if (homeMovies.length > 0) {
                homeMovies = parseMovies(homeMovies);
                outputMovies(homeMovies);
            } else {
                var para = document.createElement("p");
                var text = document.createTextNode('Cannot find any "at home" movies. Flip me over to see your Netflix queue.');
                para.appendChild(text);
                para.id = "error";
                document.getElementById("front-output").appendChild(para);
            }

            if (queueMovies.length > 0) {
                queueMovies = parseQueue(queueMovies);
                outputQueue(queueMovies);
            } else {
                var para = document.createElement("p");
                var text = document.createTextNode('Cannot find any movies in your Netflix queue.');
                para.appendChild(text);
                para.id = "error";
                document.getElementById("back-output").appendChild(para);
            }
        } else {
            var para = document.createElement("p");
            var text = document.createTextNode("Cannot connect to the Netflix web page. Please try again in a few moments or check your internet connection.");
            para.appendChild(text);
            para.id = "error";
            document.getElementById("front-output").appendChild(para);
            gFrontScrollArea.refresh();
        }
    }
}

function parseMovies(arr) {
    var titles = new RegExp(gNFMovieTitle);
    var dates = new RegExp(gNFMovieDate);
    var count;
    var nameArr;
    var dateArr;
    var movies = [];

    for (var i = 0; i < arr.length; i++) {
        // Netflix does some goofy stuff to the queue if you've
        // ordered a replacement disk.
        var movieStats = [];

        nameArr = titles.exec(arr[i]);
        if (nameArr != null) {
            movieStats.push(nameArr[1]);
            movieStats.push(nameArr[2]);
    
            dateArr = dates.exec(arr[i]);
            if (null == dateArr) {
                movieStats.push("Unknown");
                movieStats.push("Unknown");
                movieStats.push("Unknown");
            } else {
                movieStats.push(dateArr[1]);
                movieStats.push(dateArr[2]);
                movieStats.push(dateArr[3]);
            }
            movies.push(movieStats);
        }
    }
    return movies;
}

function parseQueue(arr) {
    var titles = new RegExp(gNFMovieTitle);
    var nameArr;
    var queue = [];

    for (var i = 0; i < arr.length; i++) {
        var queueStats = [];
        nameArr = titles.exec(arr[i]);
        if (nameArr != null) {
            queueStats.push(nameArr[1]);
            queueStats.push(nameArr[2]);
            queue.push(queueStats);
        }
    }
    return queue;
}

function outputQueue(arr){
    for (var i = 0; i < arr.length; i++) {
        var para = document.createElement("p");
        var bold = document.createElement("b");
        var number = document.createTextNode((i+1) + " ");
        var element = document.createElement("a");
        var text = document.createTextNode(arr[i][1]);
        bold.appendChild(number);
        bold.className = "queueNumber";
        element.appendChild(text);
        element.className = "movieName";
        if (window.widget) {
            element.href="javascript:widget.openURL('" + arr[i][0] + "')";
        }
        para.appendChild(bold);
        para.appendChild(element);
        document.getElementById("back-output").appendChild(para);
    }
    gBackScrollArea.refresh();
}

function outputMovies(arr) {
    for (var i = 0; i < arr.length; i++) {
        var element = document.createElement("a");
        var text = document.createTextNode(arr[i][1]);
        element.appendChild(text);
        element.className = "movieName";
        if (window.widget) {
            element.href="javascript:widget.openURL('" + arr[i][0] + "')";
        }
        document.getElementById("front-output").appendChild(element);

        element = document.createElement("p");
        var day = (arr[i][2] == "Unknown") ?
                  arr[i][2] :
                  arr[i][2] + "/" + arr[i][3] + "/" + arr[i][4];
        text = document.createTextNode("Est. Arrival: " + day);
        element.appendChild(text);
        element.className = "movieDate";
        document.getElementById("front-output").appendChild(element);
    }
    gFrontScrollArea.refresh();
}
